package com.aiti.lulian.workflow;




import com.aiti.lulian.mapper.ProcessDefinitionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.List;


@Service
public class ProcessDefinitionManager {

    @Autowired
    private ProcessDefinitionMapper processDefinitionMapper;

    public int save(ProcessDefinition processDefinition) {
        return processDefinitionMapper.insert(processDefinition);
    }

    public ProcessDefinition findById(String id) {
        return processDefinitionMapper.selectById(id);
    }

    public ProcessDefinition findActiveById(String id) {
        return processDefinitionMapper.findByIdAndIsActive(id, true);
    }

    public List<ProcessDefinition> findAllActive() {
        return processDefinitionMapper.findByIsActive(true);
    }

    @Transactional
    public int deployProcess(String processJson) {
        try {
            // 解析JSON获取流程定义信息
            ProcessDefinition definition = parseProcessDefinitionFromJson(processJson);

            // 检查是否已存在同名同版本的流程定义
            List<ProcessDefinition> existing = processDefinitionMapper
                    .findByNameAndVersion(definition.getName(), definition.getVersion());

            if (!CollectionUtils.isEmpty(existing)) {
                // 如果已存在，停用旧版本
                ProcessDefinition oldDefinition = existing.get(0);
                oldDefinition.setIsActive(false);
                processDefinitionMapper.insert(oldDefinition);
            }

            // 保存新流程定义
            return processDefinitionMapper.insert(definition);
        } catch (Exception e) {
            throw new RuntimeException("Failed to deploy process: " + e.getMessage(), e);
        }
    }

    private ProcessDefinition parseProcessDefinitionFromJson(String processJson) {

        try {

            ProcessDefinition definition = new ProcessDefinition();
            definition.setId("process_" + System.currentTimeMillis());
            definition.setName("");
            definition.setVersion(1);
            definition.setDefinitionJson(processJson);
            return definition;
        } catch (Exception e) {
            throw new RuntimeException("解析失败", e);
        }
    }

    @Transactional
    public void deactivateProcess(String processDefinitionId) {
        ProcessDefinition processDefinition = processDefinitionMapper.selectById(processDefinitionId);
        if (processDefinition != null) {

            processDefinition.setIsActive(false);
            processDefinitionMapper.insert(processDefinition);
        }
    }
}
